package com.augrain.microframework.trace.instrument.rabbitmq;

import com.augrain.microframework.core.spring.SpringUtils;
import com.augrain.microframework.core.util.IpUtils;
import com.augrain.microframework.core.util.StringUtils;
import com.augrain.microframework.trace.TraceConstant;
import com.augrain.microframework.trace.common.spanid.SpanIdGenerator;
import com.augrain.microframework.trace.context.TraceContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.core.MessageProperties;

/**
 * 将traceId, spanId设置消息header中
 *
 * @author biaoy
 * @since 2023/08/10
 */
@Slf4j
public class BeforeMessagePostProcessor implements MessagePostProcessor {
    @Override
    public Message postProcessMessage(Message message) throws AmqpException {
        String traceId = TraceContext.getTraceId();
        if (StringUtils.isNotEmpty(traceId)) {
            MessageProperties messageProperties = message.getMessageProperties();
            messageProperties.setHeader(TraceConstant.TRACE_ID, traceId);
            messageProperties.setHeader(TraceConstant.SPAN_ID, SpanIdGenerator.generateNextSpanId());
            messageProperties.setHeader(TraceConstant.FROM_APP, SpringUtils.getApplicationName());
            messageProperties.setHeader(TraceConstant.FROM_IP, IpUtils.getLocalIp());
        } else {
            if (log.isDebugEnabled()) {
                log.debug("[TRACE]本地threadLocal变量没有正确传递traceId,本次调用不传递traceId");
            }
        }
        return message;
    }
}
